package com.mike.bdb.ui.support;

import java.util.concurrent.TimeUnit;

import org.eclipse.swt.SWT;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.MessageBox;
import org.eclipse.swt.widgets.ProgressBar;
import org.eclipse.swt.widgets.Shell;

import com.mike.bdb.util.BackThread;

/** 抽象后台线程对话框 */
public abstract class AbstractBackGroundWorkDialog {
	
	protected Shell shell;
	
	/** 后台线程 */
	protected BackThread backThread;
	
	/** 进度条 */
	protected ProgressBar progressBar;
	
	/** 完成提示 */
	protected Label info;
	
	/** 具体的后台线程初始化和启动 */
	protected abstract void startBackWorkThread();
	
	public static final int FINISH_SELECTION = 100;
	
	/** 
	 * 后台进度条更新线程 要放在swt循环之前 如下
	 *  while (!shell.isDisposed()) {
	 *		if (!display.readAndDispatch()) {
	 *			display.sleep();
	 *		}
	 *	} 
	 * */
	protected void startUpdateThread() {
		
		startBackWorkThread();
		
		new Thread() {
			@Override
			public void run() {
				if(null == backThread) return;
				if(null == progressBar) return;
				Display display = Display.getDefault();
				while(backThread.getProgress() < FINISH_SELECTION) {
					if(progressBar.isDisposed() || display.isDisposed()) return;
					display.asyncExec(new Runnable() {
						@Override public void run() {
							if(progressBar.isDisposed()) return;
							progressBar.setSelection(backThread.getProgress());
						}
					});
					try {
						TimeUnit.MICROSECONDS.sleep(200);
					} catch (InterruptedException e) {
						Thread.currentThread().interrupt();
					}
				}
				display.asyncExec(new Runnable() {
					@Override public void run() {
						closeWindow();
					}
				});
			}
		}.start();
	}
	
	protected void closeWindow() {
		if(null == shell) return;
		if(null == info) return;
		if(progressBar.isDisposed()) return;
		progressBar.setSelection(FINISH_SELECTION);
		info.setText(" 完成!");
		if(shell.isDisposed()) return;
		shell.dispose();
		alert();
	}
	
	private void alert() {
		Display.getDefault().syncExec(new Runnable() {
			
			@Override
			public void run() {
				Shell shell = new Shell();
				MessageBox mb = new MessageBox(shell, SWT.ICON_INFORMATION | SWT.OK);
				mb.setText("系统提示");
				mb.setMessage("操作顺利完成!");
				mb.open();
			}
		});
	}
}
